package com.yuexun.dhdoctor.module.survey.ui;

import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.survey.adapter.SurveyTopicAdapter;
import com.yuexun.dhdoctor.module.survey.bean.StartSurveyBean;
import com.yuexun.dhdoctor.module.survey.bean.SurveyAnswerDtlBean;
import com.yuexun.dhdoctor.module.survey.bean.SurveyDtlBean;
import com.yuexun.dhdoctor.module.survey.bean.UpdateSurveyBean;
import com.yuexun.dhdoctor.module.survey.model.impl.SurveyModel;
import com.yuexun.dhdoctor.module.survey.presenter.impl.SurveyDtlPresenter;
import com.yuexun.dhdoctor.module.survey.presenter.impl.UpdateSurveyPresenter;
import com.yuexun.dhdoctor.module.survey.ui.view.ISurveyDtlView;
import com.yuexun.dhdoctor.module.survey.ui.view.IUpdateSurveyView;
import com.yuexun.dhdoctor.widget.ActionSheetDialog;
import com.yuexun.dhdoctor.widget.LinearLayoutForListView;
import com.yuexun.dhdoctor.widget.LoadingDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangt on 2017/8/2.
 */

public class Act_Survey_Start extends BaseKJActivity implements ISurveyDtlView, IUpdateSurveyView {

    @Bind(R.id.title_tv)
    TextView title;
    @Bind(R.id.ib_right)
    TextView right;

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.tv_template_name)
    TextView tvTemplateName;
    @Bind(R.id.tv_y_time)
    TextView tvYTime;
    @Bind(R.id.tv_people)
    TextView tvPeople;
    @Bind(R.id.tv_d_people)
    TextView tvDPeople;
    @Bind(R.id.tv_num)
    TextView tvNum;
    @Bind(R.id.tv_department)
    TextView tvDepartment;
    @Bind(R.id.tv_zhiwu)
    TextView tvZhiwu;
    @Bind(R.id.tv_time)
    TextView tvTime;

    @Bind(R.id.topic_list)
    LinearLayoutForListView topicLayout;
    @Bind(R.id.ll_head)
    LinearLayout llHead;
    @Bind(R.id.tv_head)
    TextView tvHead;
    @Bind(R.id.tv_tail)
    TextView tvTail;

    private SurveyTopicAdapter adapter;

    //get：我收到的、草稿箱  submit：我提交的
    private String pagetType = "";
    private int surveyId;
    private int templateId;
    private String createName;

    private int answerId;
    //题目列表
    private List<SurveyDtlBean.DtlListBean> topicList = new ArrayList<>();
    //人员详情
    private SurveyAnswerDtlBean surveyAnswerDtl;
    //已选题目列表
    private List<SurveyAnswerDtlBean.ListBeanX> answerList = new ArrayList<>();

    private SurveyDtlPresenter dtlPresenter;
    private UpdateSurveyPresenter updatePresenter;

    private List<UpdateSurveyBean> updateAnswer = new ArrayList<>();
    private LoadingDialog loadingDialog;

    @Override
    public void setRootView() {
        super.setRootView();
        setContentView(R.layout.act_survey_start);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        pagetType = getIntent().getStringExtra("type");
        surveyId = getIntent().getIntExtra("surveyId", 0);
        templateId = getIntent().getIntExtra("templateId", 0);
        createName = getIntent().getStringExtra("createName");
        if (pagetType.equals("submit")) {
            right.setVisibility(View.GONE);
        }
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();

        dtlPresenter = new SurveyDtlPresenter(new SurveyModel(), this);
        updatePresenter = new UpdateSurveyPresenter(new SurveyModel(), this);

        ApiGetStart();
        ApiGetAnswerDtl();
    }

    //开始答卷请求
    private void ApiGetStart() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("surveyId", surveyId + "");
        dtlPresenter.startSurvey(params);
    }

    //请求答案详情
    private void ApiGetAnswerDtl() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("surveyId", surveyId + "");
        dtlPresenter.getSurveyAnswerDtl(params);
    }

    //请求题目详情
    private void ApiGetDtl() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("templateId", templateId + "");
        dtlPresenter.getSurveyDtl(params);
    }

    //提交答案
    private void ApiForSubmitAnswer(int answerStatus, String dtlJson) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("answerId", answerId + "");
        params.put("answerStatus", answerStatus + "");//1提交答卷 0暂存答卷
        params.put("dtlJson", dtlJson);
        updatePresenter.updateSurveyAnswer(params);
    }

    @OnClick({R.id.back, R.id.ib_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ib_right:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date endDate = sdf.parse(surveyAnswerDtl.getSurveyEndTime());
                    if (new Date().before(endDate)) {
                        showSubmitDialog();
                    } else {
                        ViewInject.toast("调查时间已结束，不能提交");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    //提取全部答案
    private String getAllAnswer(boolean isAllSelect) {
        updateAnswer.clear();

        final int childcount = topicLayout.getChildCount();
        for (int i = 0; i < childcount; i++) {
            View view = topicLayout.getChildAt(i);
            LinearLayout checkboxGroup = (LinearLayout) view.findViewById(R.id.checkbox_group);
            EditText other = (EditText) view.findViewById(R.id.et_other);

            UpdateSurveyBean item = new UpdateSurveyBean();
            item.setDtlId(topicList.get(i).getDtlId() + "");
            if (topicList.get(i).getShowType().equals("1") || topicList.get(i).getShowType().equals("3")) {    //单选 / 复选
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSurveyBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    CheckBox checkbox = (CheckBox) checkboxGroup.getChildAt(x);
                    UpdateSurveyBean.ListBean item_1 = new UpdateSurveyBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);
                    } else {
                        noSelect++;
                        item_1.setDtlAnswer(-1);
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("2") || topicList.get(i).getShowType().equals("4")) { //单选+其他 / 复选其他
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSurveyBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    CheckBox checkbox = (CheckBox) checkboxGroup.getChildAt(x);
                    UpdateSurveyBean.ListBean item_1 = new UpdateSurveyBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);
                    } else {
                        item_1.setDtlAnswer(-1);
                    }
                    if (x == (child_1 - 1) && checkbox.getText().toString().equals("其他") && checkbox.isChecked()) {
                        item_1.setDtlValue(other.getText().toString().trim());
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("5")) {         //文本框
                item.setDtlValue(other.getText().toString().trim());
            }
            updateAnswer.add(item);
        }
        return JSON.toJSONString(updateAnswer);
    }

    //暂存答卷、提交答卷
    private void showSubmitDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("提交答卷", ActionSheetDialog.SheetItemColor.Red,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                loadingDialog.show();
                                if (TextUtils.isEmpty(getAllAnswer(true))) {
                                    ViewInject.toast("有未选择的题目");
                                    loadingDialog.dismiss();
                                } else {
                                    ApiForSubmitAnswer(1, getAllAnswer(true));
                                }
                            }
                        })
                .addSheetItem("暂存答卷", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                loadingDialog.show();
                                ApiForSubmitAnswer(0, getAllAnswer(false));
                            }
                        });
        actionSheetDialog.show();
    }

    //开始答卷
    @Override
    public void startSurvey(BaseEntity<StartSurveyBean> bean) {
        if (bean.getStatus().equals("200")) {
            answerId = bean.getDatas().get(0).getAnswerId();
        } else {
            ViewInject.toast("开始答卷失败");
        }
    }

    //人员详情
    @Override
    public void showSurveyAnswerDtl(BaseEntity<SurveyAnswerDtlBean> bean) {
        if (bean.getStatus().equals("200")) {
            surveyAnswerDtl = bean.getDatas().get(0);
            answerList = bean.getDatas().get(0).getList();

            ApiGetDtl();
            showAnswerDtl();
        } else {
            ViewInject.toast("获取答卷详情错误");
        }
    }

    //显示详情
    private void showAnswerDtl() {
        if (pagetType.equals("submit")) {
            title.setText(surveyAnswerDtl.getSurveyName());
        }
        tvTitle.setText(surveyAnswerDtl.getSurveyName());
        tvType.setText(surveyAnswerDtl.getTypeName());
        tvTemplateName.setText(surveyAnswerDtl.getTemplateTitle());
        tvYTime.setText(surveyAnswerDtl.getSurveyStartTime() + "~" + surveyAnswerDtl.getSurveyEndTime());
        tvPeople.setText(createName);
        tvDPeople.setText(surveyAnswerDtl.getAccountName());
        tvNum.setText(surveyAnswerDtl.getJobNum() + "");
        tvDepartment.setText(surveyAnswerDtl.getDepart());
        tvZhiwu.setText(surveyAnswerDtl.getPosition().split(";")[0]);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(surveyAnswerDtl.getSurveyStartTime());
            Date endDate = sdf.parse(surveyAnswerDtl.getSurveyEndTime());
            long l = endDate.getTime() - startDate.getTime();
            long H = l / (1000 * 60) / 60;
            long M = l / (1000 * 60) % 60;
            if (H > 0 && M > 0) {
                tvTime.setText(H + "时" + M + "分");
            } else if (H == 0) {
                tvTime.setText(M + "分");
            } else if (M == 0) {
                tvTime.setText(H + "时");
            } else {
                tvTime.setText(M + "分");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    //题库详情
    @Override
    public void showSurveyDtl(BaseEntity<SurveyDtlBean> bean) {
        if (bean.getStatus().equals("200")) {

            if (!TextUtils.isEmpty(bean.getDatas().get(0).getIntroduce())) {
                llHead.setVisibility(View.VISIBLE);
                tvHead.setText(bean.getDatas().get(0).getIntroduce());
            }
            if (!TextUtils.isEmpty(bean.getDatas().get(0).getClosing())) {
                tvTail.setVisibility(View.VISIBLE);
                tvTail.setText(bean.getDatas().get(0).getClosing());
            }

            topicList = bean.getDatas().get(0).getDtlList();
            if (pagetType.equals("get")) {
                adapter = new SurveyTopicAdapter(this, topicList, true, answerList);
            } else if (pagetType.equals("submit")) {
                adapter = new SurveyTopicAdapter(this, topicList, false, answerList);
            }
            topicLayout.setAdapter(adapter);
            loadingDialog.dismiss();
        } else {
            ViewInject.toast("获取题目详情错误");
        }
    }

    @Override
    public void updateSurvey(BaseEntity<String> bean) {
        if ("200".equals(bean.getStatus())) {
            ViewInject.toast("提交成功");
            finish();
        } else {
            ViewInject.toast("提交失败");
        }
        loadingDialog.dismiss();
    }
}
